package com.sunday.android.fangdaifu.bukong.fragment.tab;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.adapter.HouseListAdapter;
import com.sunday.android.fangdaifu.bukong.entity.House;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/11/6.
 */

public class BaoFragment1 extends LazyFragment {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.emptylayout)
    EmptyLayout emptylayout;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.left_btn)
    ImageView leftBtn;


    private PopupWindow popupWindow;

    private LinearLayoutManager layoutManager;
    private HouseListAdapter adapter;
    private List<House> warnList = new ArrayList<>();

    private String searchContent;//搜索内容 === plantNo
    private long memberId;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;

    public static BaoFragment1 newInstance() {
        BaoFragment1 fragment = new BaoFragment1();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bao1, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApp.getInstance().getMemberId();
        initView();
        isPrepared = true;
        lazyLoad();
        handleRecycle();
    }

    private void initView() {
        titleView.setText("预警房屋");
        leftBtn.setVisibility(View.GONE);
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new HouseListAdapter(mContext, warnList);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).color(Color.parseColor("#999999")).build());
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        getData();
    }


    private void loading() {
        if (!refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(true);
        }
    }

    private void getData() {
        loading();
        Call<ResultDO<List<House>>> call = ApiClient.getApiAdapter().getHouseList(memberId, searchContent, pageNo, pageSize);
        call.enqueue(new Callback<ResultDO<List<House>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<House>>> call, Response<ResultDO<List<House>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    if (pageNo==1){
                        warnList.clear();
                    }
                    warnList.addAll(response.body().getResult());
                    if (warnList.isEmpty()) {
                        emptylayout.setErrorType(EmptyLayout.NODATA);
                        emptylayout.setErrorMessage("暂无数据");
                    } else {
                        emptylayout.setVisibility(View.GONE);
                    }
                    if (response.body().getResult().size() == pageSize) {
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<House>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private int pageNo = 1, pageSize = 10;
    private boolean isCanloadMore = false;
    private int lastVisibleItem;

    private void handleRecycle() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy > 0;
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
